package com.controller.backend.noti;

import com.entity.Notification;
import com.entity.User;
import com.util.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@WebServlet("/backend/notification")
public class BackNotificationServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Notification> notifications = new ArrayList<>();
        String sql = "select * from notifications";
        try (Connection conn = DataSourceUtils.getConnection();
             PreparedStatement st = conn.prepareStatement(sql)) {
            try(ResultSet rs = st.executeQuery(sql)) {
                while (rs.next()) {
                    int id = rs.getInt("id");
                    String title = rs.getString("title");
                    String content = rs.getString("content");
                    Date addTime = rs.getDate("add_time");
                    Notification notification = new Notification(id, title, content, addTime);
                    notifications.add(notification);
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        User user = (User) req.getSession().getAttribute("user");
        if (user != null) {
            req.setAttribute("username", user.getUserName());
            req.setAttribute("notifications", notifications);
            req.getRequestDispatcher("/WEB-INF/backend/notification.jsp").forward(req, resp);
        } else {
            resp.sendRedirect(req.getContextPath() + "/login");
        }
    }
}